from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity, verify_jwt_in_request
from backend.app import db
def get_ai_prediction_model():
    from backend.models.ai_prediction import AIPrediction
    return AIPrediction
from sqlalchemy import func
from datetime import datetime, timedelta

reports_bp = Blueprint('reports', __name__)

def optional_jwt_required():
    """可选的JWT验证装饰器"""
    def wrapper(fn):
        def decorator(*args, **kwargs):
            try:
                verify_jwt_in_request()
            except:
                # 如果没有token或token无效，继续执行但不记录用户信息
                pass
            return fn(*args, **kwargs)
        return decorator
    return wrapper

@reports_bp.route('/summary', methods=['GET'])
@optional_jwt_required()
def get_summary_report():
    """获取汇总报表"""
    try:
        current_app.logger.info('开始获取汇总报表')
        AIPrediction = get_ai_prediction_model()
        
        # 总预测次数
        total_predictions = AIPrediction.query.count()
        
        # 已验证的预测次数
        verified_predictions = AIPrediction.query.filter(
            AIPrediction.actual_result.isnot(None)
        ).count()
        
        # 总中奖金额
        total_win_amount = db.session.query(func.sum(AIPrediction.win_amount)).scalar() or 0
        
        # 中奖次数统计
        win_stats = db.session.query(
            func.count(AIPrediction.id).label('total'),
            func.sum(func.case([(AIPrediction.win_amount > 0, 1)], else_=0)).label('wins')
        ).filter(AIPrediction.actual_result.isnot(None)).first()
        
        win_rate = (win_stats.wins / win_stats.total * 100) if win_stats.total > 0 else 0
        
        # 最近7天的预测统计
        seven_days_ago = datetime.now() - timedelta(days=7)
        recent_predictions = AIPrediction.query.filter(
            AIPrediction.created_at >= seven_days_ago
        ).count()
        
        result = {
            'total_predictions': total_predictions,
            'verified_predictions': verified_predictions,
            'total_win_amount': float(total_win_amount),
            'win_rate': round(win_rate, 2),
            'recent_predictions': recent_predictions
        }
        
        current_app.logger.info(f'汇总报表获取成功: {result}')
        return jsonify(result), 200
        
    except Exception as e:
        current_app.logger.error(f'获取汇总报表失败: {str(e)}')
        # 返回默认数据而不是错误
        default_result = {
            'total_predictions': 0,
            'verified_predictions': 0,
            'total_win_amount': 0.0,
            'win_rate': 0.0,
            'recent_predictions': 0
        }
        return jsonify(default_result), 200

@reports_bp.route('/winning-analysis', methods=['GET', 'OPTIONS'])
@optional_jwt_required()
def get_winning_analysis():
    """获取中奖分析报表"""
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return '', 200
    
    try:
        current_app.logger.info('开始获取中奖分析报表')
        AIPrediction = get_ai_prediction_model()
        
        # 获取已验证的预测记录
        predictions = AIPrediction.query.filter(
            AIPrediction.actual_result.isnot(None)
        ).order_by(AIPrediction.created_at.desc()).all()
        
        # 分析中奖情况
        winning_analysis = {
            'total_verified': len(predictions),
            'total_wins': 0,
            'total_amount': 0,
            'win_levels': {
                '一等奖': 0,
                '二等奖': 0,
                '三等奖': 0,
                '四等奖': 0,
                '五等奖': 0,
                '六等奖': 0
            },
            'monthly_stats': {}
        }
        
        for prediction in predictions:
            if prediction.win_amount > 0:
                winning_analysis['total_wins'] += 1
                winning_analysis['total_amount'] += float(prediction.win_amount)
                
                # 统计中奖等级
                if prediction.win_info:
                    for level in winning_analysis['win_levels'].keys():
                        if level in prediction.win_info:
                            winning_analysis['win_levels'][level] += 1
                            break
                
                # 按月统计
                month_key = prediction.created_at.strftime('%Y-%m')
                if month_key not in winning_analysis['monthly_stats']:
                    winning_analysis['monthly_stats'][month_key] = {
                        'predictions': 0,
                        'wins': 0,
                        'amount': 0
                    }
                winning_analysis['monthly_stats'][month_key]['wins'] += 1
                winning_analysis['monthly_stats'][month_key]['amount'] += float(prediction.win_amount)
            
            # 统计预测次数
            month_key = prediction.created_at.strftime('%Y-%m')
            if month_key not in winning_analysis['monthly_stats']:
                winning_analysis['monthly_stats'][month_key] = {
                    'predictions': 0,
                    'wins': 0,
                    'amount': 0
                }
            winning_analysis['monthly_stats'][month_key]['predictions'] += 1
        
        current_app.logger.info(f'中奖分析报表获取成功: 总验证{winning_analysis["total_verified"]}条，中奖{winning_analysis["total_wins"]}次')
        return jsonify(winning_analysis), 200
        
    except Exception as e:
        current_app.logger.error(f'获取中奖分析报表失败: {str(e)}')
        # 返回默认数据而不是错误
        default_result = {
            'total_verified': 0,
            'total_wins': 0,
            'total_amount': 0,
            'win_levels': {
                '一等奖': 0,
                '二等奖': 0,
                '三等奖': 0,
                '四等奖': 0,
                '五等奖': 0,
                '六等奖': 0
            },
            'monthly_stats': {}
        }
        return jsonify(default_result), 200

@reports_bp.route('/prediction-trends', methods=['GET', 'OPTIONS'])
@optional_jwt_required()
def get_prediction_trends():
    """获取预测趋势报表"""
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return '', 200
    
    try:
        current_app.logger.info('开始获取预测趋势报表')
        # 获取最近30天的预测数据
        thirty_days_ago = datetime.now() - timedelta(days=30)
        
        AIPrediction = get_ai_prediction_model()
        # 按日期统计预测次数
        daily_stats = db.session.query(
            func.date(AIPrediction.created_at).label('date'),
            func.count(AIPrediction.id).label('count')
        ).filter(
            AIPrediction.created_at >= thirty_days_ago
        ).group_by(
            func.date(AIPrediction.created_at)
        ).order_by(
            func.date(AIPrediction.created_at)
        ).all()
        
        # 按日期统计中奖情况
        daily_wins = db.session.query(
            func.date(AIPrediction.created_at).label('date'),
            func.sum(func.case([(AIPrediction.win_amount > 0, 1)], else_=0)).label('wins'),
            func.sum(AIPrediction.win_amount).label('amount')
        ).filter(
            AIPrediction.created_at >= thirty_days_ago,
            AIPrediction.actual_result.isnot(None)
        ).group_by(
            func.date(AIPrediction.created_at)
        ).order_by(
            func.date(AIPrediction.created_at)
        ).all()
        
        # 合并数据
        trends = {}
        for stat in daily_stats:
            date_str = stat.date.strftime('%Y-%m-%d')
            trends[date_str] = {
                'date': date_str,
                'predictions': stat.count,
                'wins': 0,
                'amount': 0
            }
        
        for win in daily_wins:
            date_str = win.date.strftime('%Y-%m-%d')
            if date_str in trends:
                trends[date_str]['wins'] = win.wins
                trends[date_str]['amount'] = float(win.amount) if win.amount else 0
        
        result = {'trends': list(trends.values())}
        current_app.logger.info(f'预测趋势报表获取成功: {len(trends)}天数据')
        return jsonify(result), 200
        
    except Exception as e:
        current_app.logger.error(f'获取预测趋势报表失败: {str(e)}')
        # 返回默认数据而不是错误
        default_result = {'trends': []}
        return jsonify(default_result), 200 